#include "pix5core.h"

#ifdef PIX5DEBUG

char* Debug::_log = NULL;
Object* Debug::_firstObject = NULL;
Object* Debug::_lastObject = NULL;


void Debug::init()
{
	_log = NULL;
	_firstObject = NULL;
	_lastObject = NULL;

	Object* fo = new Object();
	Object* lo = new Object();

	_firstObject = fo;
	_lastObject = lo;

	fo->__next = lo;
	lo->__prev = fo;
}

void Debug::shutdown()
{
	if(_firstObject)
	{
		Object* obj = _firstObject->__next;

		while(obj!=_lastObject)
		{
			Debug::write("Object of type \033[32;1m%s\033[m was not deleted\n",obj->__getName());
			obj = obj->__next;
		}

		Object* fo = _firstObject;
		Object* lo = _lastObject;

		_firstObject = NULL;
		_lastObject = NULL;

		delete fo;
		delete lo;
	}

	if(_log)
	{
		printf("\033[31mDEBUG LOG:\n------------------------------------------------------------\033[m\n%s\033[31m------------------------------------------------------------\033[m\n",_log);
		free(_log);
		_log = NULL;
	}
}

void Debug::registerObject(Object* obj)
{
	if(!_firstObject)
		return;
	
	obj->__prev = _firstObject;
	obj->__next = _firstObject->__next;

	obj->__prev->__next = obj;
	obj->__next->__prev = obj;
}


void Debug::unregisterObject(Object* obj)
{
	if(!_firstObject)
		return;
	
	obj->__prev->__next = obj->__next;
	obj->__next->__prev = obj->__prev;
}

void Debug::write(const char* fmt,...)
{
	va_list vl;

	va_start(vl,fmt);
	int size = vsnprintf(NULL,0,fmt,vl);

	int len = _log ? strlen(_log) : 0;
	_log = (char*)realloc(_log,size+len+1);

	va_start(vl,fmt);
	vsprintf(_log+len,fmt,vl);
}

#endif

